<template>
  <el-dialog fullscreen title="审核记录填报" v-model="dialogVisible">
    <el-form :disabled="formDisabled" ref="formRef" :model="formData" :rules="formRules" label-width="100px"
      v-loading="formLoading">
      <el-descriptions title="" border :column=4>
        <el-descriptions-item label="等级">{{ formData.levelName }}</el-descriptions-item>
        <el-descriptions-item label="区域">{{ formData.areaName }}</el-descriptions-item>
        <el-descriptions-item label="审核日期">{{ formData.auditStartDate }}</el-descriptions-item>
        <el-descriptions-item label="审核人">{{ formData.auditUserName }}</el-descriptions-item>
        <el-descriptions-item label="重要工序" :span="4"> <el-input :disabled="formDisabled" type="textarea"
            v-model="formData.importantProcesses" placeholder="请输入重要工序" /></el-descriptions-item>
        <el-descriptions-item label="近期问题" :span="4"> <el-input :disabled="formDisabled" type="textarea"
            v-model="formData.recentlyProblem" placeholder="请输入近期问题" /></el-descriptions-item>
      </el-descriptions>
    </el-form>
    <ContentWrap>
      <el-table border row-key="id" :data="formData.detailList" :stripe="true" :show-overflow-tooltip="true"
        :header-cell-style="{ background: '#e6f7ef', color: '#008c46' }">
        <el-table-column label="分类名称" align="center" prop="auditTypeName" width="100" />
        <el-table-column label="审核项" align="center" prop="configName" min-width="300" />
        <el-table-column label="审核结果" align="center" prop="auditResult" width="150">
          <template #default="scope">
            <el-select :disabled="formDisabled" v-model="scope.row.auditResult" placeholder="请选择" clearable>
              <el-option v-for="dict in getIntDictOptionsString(DICT_TYPE.AUDIT_RESULT)" :key="dict.value"
                :label="dict.label" :value="dict.value" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="问题简述" align="center" prop="remark" width="300">
          <template #default="scope">
            <el-input :disabled="formDisabled" type="textarea" v-model="scope.row.remark" placeholder="请输入问题简述" />
          </template>
        </el-table-column>
        <el-table-column label="责任人" align="center" prop="dutyUserId" width="150">
          <template #default="scope">
            <el-select :disabled="formDisabled" clearable filterable v-model="scope.row.dutyUserId"
              placeholder="请选择责任人,支持模糊搜索">
              <el-option v-for="dict in userList" :key="dict.id" :label="dict.nickname" :value="dict.id" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="计划时间" align="center" prop="planDate" width="200">
          <template #default="scope">
            <el-date-picker :disabled="formDisabled" style="width: 100%" v-model="scope.row.planDate" type="date"
              value-format="YYYY-MM-DD" placeholder="计划完成时间" />
          </template>
        </el-table-column>

        <el-table-column label="附件" min-width="320px" align="center">
          <template #default="scope">
            <UploadFile :isShowTip="false" v-model="scope.row.files" :disabled="formDisabled" />
          </template>
        </el-table-column>

      </el-table>
    </ContentWrap>

    <template #footer>
      <el-button :disabled="formDisabled" @click="submitForm(1)" type="primary">暂 存</el-button>
      <el-button :disabled="formDisabled" @click="submitForm(2)" type="primary">提 交</el-button>
      <el-button @click="dialogVisible = false">关 闭</el-button>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE, getIntDictOptionsString } from '@/utils/dict'
import { AuditPlanAreaApi, AuditPlanArea } from '@/api/business/auditplanarea'
import * as UserApi from '@/api/system/user'

/** 审核计划区域 表单 */
defineOptions({ name: 'AuditPlanAreaForm' })

//用户列表
const userList = ref([])

const initUserList = async () => {
  userList.value = await UserApi.getSimpleUserList()
}


const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  levelId: undefined,
  planId: undefined,
  areaId: undefined,
  auditStartDate: undefined,
  auditEndDate: undefined,
  auditUserId: undefined,
  status: undefined,
  areaName: undefined,
  importantProcesses: undefined,
  recentlyProblem: undefined,
  writeUserId: undefined,
  writeUserName: undefined,
  writeTime: undefined,
  sendUserId: undefined,
  sendUserName: undefined,
  sendTime: undefined,
  auditUserName: undefined,
  writeStatus: undefined,
  levelName: undefined,
  detailList: []
})
const formRules = reactive({
})
const formRef = ref() // 表单 Ref

const formDisabled = ref(false)

/** 打开弹窗 */
const open = async (type: string, id?: number) => {

  if (type == 'view') {
    formDisabled.value = true
  } else {
    formDisabled.value = false
  }

  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await AuditPlanAreaApi.getAuditPlanArea(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async (type) => {
  formData.value.writeStatus = type
  let details = formData.value.detailList

  //审核不通过的校验问题描述、责任人、预计完成时间
  for (let index = 0; index < details.length; index++) {
    const detail = details[index];
    console.log("detail", detail);

    if (detail.auditResult != 'Y') {

      if (detail.remark == null || detail.remark == undefined) {
        message.error(`第 ${index + 1} 行必须填写问题简述`);
        return
      }


      if (detail.dutyUserId == null || detail.dutyUserId == undefined) {
        message.error(`第 ${index + 1} 行必须选择责任人`);
        return
      }

      if (detail.planDate == null || detail.planDate == undefined) {
        message.error(`第 ${index + 1} 行必须选计划时间`);
        return
      }

    }
  }
  formLoading.value = true
  await AuditPlanAreaApi.updateAuditPlanArea(formData.value)
  message.success("操作成功")
  dialogVisible.value = false
  formLoading.value = false
  emit('success')

}

// 校验函数
function validateAuditPlanAreas(detailList) {
  for (let i = 0; i < detailList.length; i++) {
    const item = detailList[i];
    // 如果审核不通过的 需要添加责任人 计划时间
    if (item.auditResult != 'Y') {
      if (item.dutyUserId == undefined || item.dutyUserId == null) {
        ElMessage.error(`第 ${i + 1} 行：请选择责任人`);
        return false;
      }

      if (item.planDate == undefined || item.planDate == null) {
        ElMessage.error(`第 ${i + 1} 行：请选择计划完成时间`);
        return false;
      }

    }

  }

  return true; // 全部通过
}


/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    levelId: undefined,
    planId: undefined,
    areaId: undefined,
    auditStartDate: undefined,
    auditEndDate: undefined,
    auditUserId: undefined,
    status: undefined,
    areaName: undefined,
    importantProcesses: undefined,
    recentlyProblem: undefined,
    writeUserId: undefined,
    writeUserName: undefined,
    writeTime: undefined,
    sendUserId: undefined,
    sendUserName: undefined,
    sendTime: undefined,
    auditUserName: undefined,
    levelName: undefined,
    detailList: []
  }
  formRef.value?.resetFields()
}

/** 初始化 **/
onMounted(async () => {
  initUserList()
})

</script>



<style>
.el-descriptions {
  margin-top: 20px;
}

.cell-item {
  display: flex;
  align-items: center;
}

.margin-top {
  margin-top: 20px;
}
</style>
